/*
 * Copyright 2008-2013, David George, Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
var cacheTime = 5;

function setUserArea(cred) {
    arry = cred.split(',');

    html = "<a href='#'>" +  arry[0] + "</a><ul class='dropdown'>";
    if (isBlank(arry[1])) {
        html += '<li><a href="login.jsp">Sign In</a></li>';
        html += '<li><a href="register.do">Register</a></li>';
    } else {
        if (arry[1].search('editors') !== -1) {
            html += '<li><a href="j_spring_security_logout">Sign Out</a></li>';
            html += '<li><li><a href="edit.do?name=' + pageName +'">Edit Page</a></li></li>';
        }
        if (arry[1].search('ROLE_ADMIN') !== -1) {
            html += '<li><a href="adminTool.do?pageName=' + pageName +'" target="_new">Administration</a></li>';
        }
    }
    html += "</ul>";
    $('#usernameResult').html(html);
}

function checkCredentials(credCallback) {
	try
	  {
		var cred = $.cookie("magUserId");
	  }
	catch(err)
	  {
	  alert("err " + err)
	  }

    if (!cred) {
        $.get('getCredentials.do', 
        	function(response) {
	            var date = new Date();
	            date.setTime(date.getTime() + (cacheTime * 60 * 1000));
	            $.cookie("magUserId", response, { expires: date, path:'/'});
	            credCallback(response);
        	}
        );
    } else {
    	credCallback(cred);
    }
}

function isBlank(val){
    var i = 0;
	if (!val) { 
    	return true;
    }
    for(i=0; i<val.length; i++) {
        if ((val.charAt(i)!==' ') && (val.charAt(i)!=='\t') && (val.charAt(i)!=='\n') && (val.charAt(i)!=='\r')) {
        	return false;
        }
    }
    return true;
}

